package cn.cdutetc.library.controller;

import cn.cdutetc.library.common.ApiResponse;
import cn.cdutetc.library.common.ExcelUtils;
import cn.cdutetc.library.entity.dto.*;
import cn.cdutetc.library.service.BookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图书管理控制器
 */
@RestController
@RequestMapping("/api/books")
@Tag(name = "图书管理", description = "图书信息管理相关接口")
public class BookController {

    @Autowired
    private BookService bookService;


    @GetMapping("/page")
    @Operation(summary = "分页查询图书", description = "根据条件分页查询图书信息")
    public ApiResponse<IPage<BookVO>> getBooks(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "关键字") @RequestParam(required = false) String keyword,
            @Parameter(description = "分类名称") @RequestParam(required = false) String categoryName,
            @Parameter(description = "分类ID") @RequestParam(required = false) Integer categoryId) {
        IPage<BookVO> result;
        if (categoryId != null) {
            result = bookService.pageBooks(page, size, keyword, categoryId);
        } else {
            result = bookService.pageBooks(page, size, keyword, categoryName);
        }
        return ApiResponse.success(result);
    }

    @GetMapping("/{bookId}")
    @Operation(summary = "获取图书详情", description = "根据ID获取图书详细信息")
    public ApiResponse<BookVO> getBook(@PathVariable Integer bookId) {
        BookVO book = bookService.getBookById(bookId);
        return ApiResponse.success(book);
    }

    @PostMapping
    @Operation(summary = "添加图书", description = "添加新的图书信息")
    public ApiResponse<Integer> addBook(@RequestBody BookCreateDTO bookCreateDTO) {
        Integer bookId = bookService.createBook(bookCreateDTO);
        return ApiResponse.success(bookId);
    }

    @PutMapping("/{bookId}")
    @Operation(summary = "更新图书", description = "更新图书信息")
    public ApiResponse<Boolean> updateBook(@PathVariable Integer bookId, @RequestBody BookUpdateDTO bookUpdateDTO) {
        // 设置图书ID到DTO中
        bookUpdateDTO.setBookId(bookId);
        boolean result = bookService.updateBook(bookUpdateDTO);
        return ApiResponse.success(result);
    }

    @DeleteMapping("/{bookId}")
    @Operation(summary = "删除图书", description = "删除图书信息")
    public ApiResponse<Boolean> deleteBook(@PathVariable Integer bookId) {
        boolean result = bookService.deleteBook(bookId);
        return ApiResponse.success(result);
    }

    @GetMapping("/isbn/{isbn}")
    @Operation(summary = "根据ISBN获取图书", description = "根据ISBN获取图书详情")
    public ApiResponse<BookVO> getBookByIsbn(@PathVariable String isbn) {
        BookVO bookVO = bookService.getBookByIsbn(isbn);
        return ApiResponse.success(bookVO);
    }

    @PostMapping("/{bookId}/increase-stock")
    @Operation(summary = "增加库存", description = "增加图书库存数量")
    public ApiResponse<Boolean> increaseStock(
            @PathVariable Integer bookId,
            @Parameter(description = "增加数量") @RequestParam Integer count) {
        boolean result = bookService.increaseStock(bookId, count);
        return ApiResponse.success(result);
    }

    @PostMapping("/{bookId}/decrease-stock")
    @Operation(summary = "减少库存", description = "减少图书库存数量")
    public ApiResponse<Boolean> decreaseStock(
            @PathVariable Integer bookId,
            @Parameter(description = "减少数量") @RequestParam Integer count) {
        boolean result = bookService.decreaseStock(bookId, count);
        return ApiResponse.success(result);
    }


    @GetMapping("/{bookId}/status-statistics")
    @Operation(summary = "获取图书状态统计", description = "获取图书各状态条目的数量统计")
    public ApiResponse<java.util.Map<String, Object>> getBookStatusStatistics(@PathVariable Integer bookId) {
        java.util.Map<String, Object> result = bookService.getBookStatusStatistics(bookId);
        return ApiResponse.success(result);
    }

    @PutMapping("/items/{itemId}/status")
    @Operation(summary = "更新图书条目状态", description = "更新单个图书条目的状态")
    public ApiResponse<Boolean> updateBookItemStatus(
            @PathVariable Integer itemId,
            @Parameter(description = "状态") @RequestParam String status,
            @Parameter(description = "备注") @RequestParam(required = false) String remark) {
        boolean result = bookService.updateBookItemStatus(itemId, status, remark);
        return ApiResponse.success(result);
    }


    @PostMapping("/importFromPath")
    @Operation(summary = "批量导入图书（从文件路径）", description = "通过上传Excel文件批量导入图书数据")
    public ApiResponse<String> importBooksFromPath(@RequestParam("file") org.springframework.web.multipart.MultipartFile file) {
        try {
            String result = bookService.importBooksFromPath(file);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("导入失败: " + e.getMessage());
        }
    }


    @GetMapping("/exportToPath")
    @Operation(summary = "导出图书信息到本地路径", description = "导出图书数据到本地Excel文件")
    public ApiResponse<String> exportBooksToPath(
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword) {
        try {
            String filePath = bookService.exportBooksToPath(keyword);
            return ApiResponse.success(filePath);
        } catch (Exception e) {
            return ApiResponse.error("导出失败: " + e.getMessage());
        }
    }

    @GetMapping("/template")
    @Operation(summary = "下载导入模板", description = "下载图书导入Excel模板")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            bookService.downloadTemplate(response);
        } catch (Exception e) {
            throw new RuntimeException("下载模板失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/categories")
    @Operation(summary = "获取图书分类列表", description = "获取所有图书分类信息")
    public ApiResponse<List<Map<String, Object>>> getBookCategories() {
        try {
            List<Map<String, Object>> categories = bookService.getBookCategories();
            return ApiResponse.success(categories);
        } catch (Exception e) {
            return ApiResponse.error("获取分类列表失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/validate-isbn")
    @Operation(summary = "验证ISBN", description = "验证ISBN是否已存在")
    public ApiResponse<Boolean> validateIsbn(@RequestParam String isbn) {
        try {
            BookVO existingBook = bookService.getBookByIsbn(isbn);
            boolean exists = existingBook != null;
            return ApiResponse.success(exists);
        } catch (Exception e) {
            return ApiResponse.error("验证ISBN失败: " + e.getMessage());
        }
    }
}